<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage, ElDialog, ElInput, ElTable, ElTableColumn } from 'element-plus'
import { Edit, View, CopyDocument, Delete, Share, Plus, Download } from '@element-plus/icons-vue'
import axios from 'axios'
import { wsManager } from '../utils/websocket'

// 获取当前时间
const currentTime = ref('')

// 更新时间的函数
const updateTime = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 按钮状态
const buttonStates = ref({
  home: '正常',
  user: '正常',
  dataImport: '正常',
  dataManage: 'normal',
  dataAnnotation: 'normal'
})

// 鼠标事件处理
const handleMouseEnter = (button) => {
  buttonStates.value[button] = '悬浮'
}

const handleMouseLeave = (button) => {
  buttonStates.value[button] = '正常'
}

const handleMouseDown = (button) => {
  buttonStates.value[button] = '点击'
}

const handleMouseUp = (button) => {
  buttonStates.value[button] = '悬浮'
}

// 路由
const router = useRouter()

// 返回主页
const goToHome = () => {
  // alert(1)
  router.push('/')
}

const goToDataManagement = () => {
  router.push('data-management')
} 

const goToDataAnnotation = () => {
  router.push('/data-annotation')
}

const wsConnected = ref(false)

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    if (!wsManager.ws || wsManager.ws.readyState !== WebSocket.OPEN) {
      await wsManager.connect()
    }
    wsConnected.value = true
  } catch (error) {
    console.error('WebSocket连接失败:', error)
  }
}

// 标注任务列表
const statusTypeMap = {
  unlabeled: 'warning',
  labeling: 'normal',
  labeled: 'success'
}
const statusLabels = {
  unlabeled: '未标注',
  labeling: '标注中',
  labeled: '已完成'
}

// 获取标注任务列表
const fetchAnnotationTasks = async () => {
  try {
    const response = await wsManager.sendMessage({
      operation: 'get_labellist',
      params: [],
      authToken: 'string'
    })
    
    if (response.status === 1) {
      annotationTasks.value = response.params.map(task => ({
        id: task.id || Math.random().toString(36).substr(2, 9),
        name: task.name,
        description: task.desc,
        status: task.labelstatus
      }))
    }
  } catch (error) {
    console.error('获取标注任务列表失败:', error)
    ElMessage.error('获取标注任务列表失败')
  }
}

// 组件挂载时获取任务列表
onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  fetchAnnotationTasks()
  initWebSocket()
})
// 模拟数据 
const annotationTasks = ref([
  {
    index: 1,
    source: '标注来源1',
    name: '进程1',
    description: '描述描述描述描述描述描述描述描述描述描述描述描述',
    status: '已标注'
  },
  {
    index: 2,
    source: '标注来源2',
    name: '进程2',
    description: '描述描述描述描述描述描述描述描述描述描述描述',
    status: '标注中'
  },
  {
    index: 3,
    source: '标注来源3',
    name: '进程3',
    description: '描述描述描述描述描述描述描述描述描述描述描述',
    status: '未标注'
  },
  {
    index: 4,
    source: '标注来源4',
    name: '进程4',
    description: '描述描述描述描述描述描述描述描述描述描述描述',
    status: '未标注'
  },
  {
    index: 5,
    source: '标注来源5',
    name: '进程5',
    description: '描述描述描述描述描述描述描述描述描述描述描述',
    status: '未标注'
  }
])

// 处理各种操作按钮的点击事件
const handleEdit = (row) => {
  console.log('编辑', row)
}

const handleAnnotate = (row) => {
  console.log('标注', row)
}

const handleDelete = (row) => {
  console.log('删除', row)
}

const handleShare = (row) => {
  console.log('分享', row)
}

const showCreateDialog = ref(false)
const showDatasetDialog = ref(false)
const selectedDatasets = ref([])
const availableDatasets = ref([])
const taskForm = ref({
  name: '',
  description: '',
  images: []
})


const handleBack = () => {
  showCreateDialog.value = false
}

const handleRefresh = () => {
  // 刷新图片预览
  console.log('刷新图片预览')
}

const handleCreate = async () => {
  showCreateDialog.value = true
  try {
    const response = await wsManager.sendMessage({
      operation: 'get_labeldata',
      params: [],
      authToken: 'string'
    })
    if (response.status === 1) {
      availableDatasets.value = response.params
    }
  } catch (error) {
    console.error('获取数据集失败:', error)
    ElMessage.error('获取数据集失败')
  }
}

const handleMultiSelect = () => {
  console.log('多选功能')
}

const handleUpload = async () => {
  showDatasetDialog.value = false
  try {
    const response = await wsManager.sendMessage({
      operation: 'newlabel_confirm',
      params: {
        name: taskForm.value.name,
        desc: taskForm.value.description,
        datalist: selectedDatasets.value
      },
      authToken: 'string'
    })
    if (response.status === 1) {
      annotationTasks.value = response.params
      ElMessage.success('创建任务成功')
    }
  } catch (error) {
    console.error('创建任务失败:', error)
    ElMessage.error('创建任务失败')
  }
}

const showAnnotationList = () => {
  listDialogVisible.value = true
}

const listDialogVisible = ref(false)
const taskList = ref([
  {
    id: 1,
    name: '标注任务1',
    description: '这是第一个标注任务的描述',
    status: '未执行'
  },
  {
    id: 2,
    name: '标注任务2',
    description: '这是第二个标注任务的描述',
    status: '执行中'
  },
  {
    id: 3,
    name: '标注任务3',
    description: '这是第三个标注任务的描述',
    status: '已完成'
  }
])

const handleAnnotateTask = (row) => {
  console.log('标注任务:', row)
}

const handleExportTask = (row) => {
  console.log('导出任务:', row)
}

const handleDeleteTask = (row) => {
  console.log('删除任务:', row)
}

</script>

<template>
  <div class="data-management">
    <!--左侧边栏 -->
    <div class="sidebar">
      <div class="logo">
        <!--<img src="/pic/dataManagement/logo-菜单左上方位置.png" alt="Logo">-->
      </div>
      <div class="nav-buttons">
        <div class="nav-button"
             @mouseenter="handleMouseEnter('dataManage')"
             @mouseleave="handleMouseLeave('dataManage')"
             @mousedown="handleMouseDown('dataManage')"
             @mouseup="handleMouseUp('dataManage');goToDataManagement()">
          <img :src="`/pic/dataManagement/数据管理-${buttonStates.dataManage === 'normal' ? '正常' : '悬浮'}.png`" alt="数据管理">
        </div>
        <div class="nav-button"
             @mouseenter="handleMouseEnter('dataAnnotation')"
             @mouseleave="handleMouseLeave('dataAnnotation')"
             @mousedown="handleMouseDown('dataAnnotation')"
             @mouseup="handleMouseUp('dataAnnotation');goToDataAnnotation()">
          <img :src="`/pic/dataManagement/数据标注-${buttonStates.dataAnnotation === 'normal' ? '正常' : '悬浮'}.png`" alt="数据标注">
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部栏 -->
      <div class="top-bar">
        <div class="system-name">算籌平台系統</div>
        <div class="home-button"
             @mouseenter="handleMouseEnter('home')"
             @mouseleave="handleMouseLeave('home')"
             @mousedown="handleMouseDown('home')"
             @mouseup="handleMouseUp('home')"
             @click="goToHome">
          <img :src="`/pic/dataManagement/首页-${buttonStates.home}.png`" alt="首页">
        </div>
        <div class="current-time">{{ currentTime }}</div>
        <div class="user-info">
          <div class="user-button"
               @mouseenter="handleMouseEnter('user')"
               @mouseleave="handleMouseLeave('user')"
               @mousedown="handleMouseDown('user')"
               @mouseup="handleMouseUp('user')">
            <img :src="`/pic/dataManagement/用户-${buttonStates.user}.png`" alt="用户">
          </div>
          <span class="username">用户：XXXX</span>
        </div>
      </div>
      
      <!--  数据标注界面  -->
      <div class="annotation-content">
        <!-- 操作工具栏 -->
        <div class="action-toolbar">
          <button class="primary-button" @click="handleCreate">数据导入</button>
          <button class="annotation-list" @click="showAnnotationList">标注任务列表</button>
          <!-- <button class="success-button" @click="handleDownload">导出数据集</button> -->
        </div>
        <!-- 任务表格区 -->
        <el-table :data="annotationTasks" style="width: 100%" height="calc(100vh - 180px)" border>
          <el-table-column type="index" label="序号" width="80"/>
          <el-table-column prop="source" label="标注进程来源" width="180" />
          <el-table-column prop="name" label="标注进程名称" width="180" />
          <el-table-column prop="description" label="描述" min-width="300" />

          <el-table-column prop="status" label="状态" width="150">
            <template #default="{ row }">
              <el-tag :type="row.status === '已标注' ? 'success' : row.status === '未标注' ? 'warning' : 'info'">
                {{ row.status }}  
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column class="operation_column" label="操作" width="320">
            <!-- <template #default="{ row }"> -->
              <!-- <el-button size="small" @click="handleEdit(row)">编辑</el-button> -->
              <div class="operation-normal-button"
                @click="handleAnnotate(row)"
                @mouseenter="handleMouseEnter('annotate')"
                @mouseleave="handleMouseLeave('annotate')"
                @mousedown="handleMouseDown('annotate')"
                @mouseup="handleMouseUp('annotate')">
                <img :src="`/pic/dataAnnotation/标注-${buttonStates.annotate === 'normal' ? '正常' : buttonStates.annotate === '悬浮' ? '悬浮' : '点击'}.png`" alt="标注" />
              </div>
              <div class="operation-delete-button"
                @click="handleDelete(row)"
                @mouseenter="handleMouseEnter('delete')"
                @mouseleave="handleMouseLeave('delete')"
                @mousedown="handleMouseDown('delete')"
                @mouseup="handleMouseUp('delete')">
                <img :src="`/pic/dataAnnotation/小删除-${buttonStates.delete === 'normal' ? '正常' : buttonStates.delete === '悬浮' ? '悬浮' : '点击'}.png`" alt="删除" />
              </div>
              <div class="operation-share-button"
                @click="handleShare(row)"
                @mouseenter="handleMouseEnter('share')"
                @mouseleave="handleMouseLeave('share')"
                @mousedown="handleMouseDown('share')"
                @mouseup="handleMouseUp('share')">
                <img :src="`/pic/dataAnnotation/分享-${buttonStates.share === 'normal' ? '正常' : buttonStates.share === '悬浮' ? '悬浮' : '点击'}.png`" alt="分享" />
              </div>
            <!-- </template> -->
          </el-table-column>
        </el-table>

        <!-- 新建标注任务弹窗 -->
        <el-dialog
          v-model="showCreateDialog"
          :title="isEditing ? '编辑标注任务' : '新建标注任务'"
          width="800px"
          custom-class="create-dialog"
        >
          <div class="dialog-content">
            <!-- 顶部名称输入 -->
            <div class="dialog-header">
              <el-input
                v-model="taskForm.name"
                :placeholder="isEditing ? '编辑任务名称' : '请输入标注任务名称'"
                clearable
                style="width: 300px"
              />
            </div>

            <!-- 中央内容区 -->
            <div class="dialog-body">
              <el-row :gutter="20">
                <!-- 左侧图片面板 -->
                <el-col :span="16">
                  <div class="image-panel">
                    <div
                      v-if="taskForm.images.length === 0"
                      @click="handleUpload"
                      class="upload-placeholder"
                    >
                      <el-icon><Upload /></el-icon>
                      <p>添加图片，仅显示筛选完成的包，供用户选择要添加的图</p>
                    </div>
                    <div v-else class="image-grid">
                      <div v-for="(file, index) in taskForm.images" :key="index" class="image-item">
                        <img :src="file.path" :alt="file.name" class="preview-image" />
                      </div>
                    </div>
                  </div>
                </el-col>

                <!-- 右侧描述输入 -->
                <el-col :span="8" style="height: 400px">
                  <el-input
                    v-model="taskForm.description"
                    type="textarea"
                    placeholder="请输入任务描述"
                    resize="none"
                    style="height: 100%; min-height: 400px; box-sizing: border-box"
                  />
                </el-col>
              </el-row>
            </div>

            <!-- 底部操作栏 -->
            <div class="dialog-footer">
              <div class="footer-actions">
                
                <div class="action-buttons">
                  <el-button text @click="showCreateDialog = false">返回</el-button>
                  <el-button @click="handleRefresh">刷新</el-button>
                  <el-button type="primary" @click="handleUpload">添加</el-button>
                  <el-button @click="handleMultiSelect">多选</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-dialog>

        <!-- 数据集选择弹窗 -->
        <el-dialog
          v-model="showPackageDialog"
          title="选择您的数据包"
          width="800px"
          custom-class="package-dialog"
        >
          <div class="dialog-content">
            <el-checkbox-group v-model="selectedDatasets">
              <el-table
                :data="availableDatasets"
                style="width: 100%"
                row-key="id"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" :reserve-selection="true" />
                <el-table-column prop="name" label="数据集名称" />
                <el-table-column label="文件数量" width="120">
                  <template #default="{ row }">
                    <el-tag type="info">{{ row.files?.length || 0 }}</el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-checkbox-group>

            <div class="dialog-footer">
              <el-button @click="showPackageDialog = false">取消</el-button>
              <el-button type="primary" @click="confirmPackageSelection">确定</el-button>
            </div>
          </div>
        </el-dialog>
        
        <el-dialog v-model="listDialogVisible" title="标注任务列表" width="70%">
          <div class="task-list-container">
            <div class="task-list-header">
              <el-button type="primary" @click="handleCreate">新建</el-button>
            </div>
            <el-table :data="taskList" style="width: 100%" border>
              <el-table-column prop="id" label="序号" width="80" />
              <el-table-column prop="name" label="标注任务" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                  <el-tag :type="row.status === '已完成' ? 'success' : row.status === '执行中' ? 'warning' : 'info'">
                    {{ row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240">
                <template #default="{ row }">
                  <el-button size="small" @click="handleAnnotateTask(row)">标注</el-button>
                  <el-button size="small" @click="handleExportTask(row)">导出</el-button>
                  <el-button size="small" type="danger" @click="handleDeleteTask(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-dialog>

      </div>
    </div>
  </div>
</template>

<style scoped>

.action-toolbar {
  display: flex;
  /* justify-content: space-between; */
  margin-bottom: 20px;
}

.action-toolbar .el-button {
  cursor: pointer;
}

.custom-table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
  font-size: 14px;
}

.custom-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
  text-align: left;
}

.custom-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
  vertical-align: middle;
}

.custom-table tr:hover td {
  background-color: #f5f7fa;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons button {
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 4px;
}
.annotation-list,
.primary-button {
  background-color: #409eff;
  color: white;
  margin-right: 20px;
}

.success-button {
  background-color: #67c23a;
  color: white;
}

.info-button {
  background-color: #909399;
  color: white;
}

.danger-button {
  background-color: #f56c6c;
  color: white;
}

.warning-button {
  background-color: #e6a23c;
  color: white;
}

.el-table .el-button {
  margin-right: 5px;
  cursor: pointer;
}

.data-management {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

.sidebar {
  width: 0px;
  background-color: #4a6baf;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

.logo img {
  width: 60px;
  height: auto;
}

.nav-buttons {
  margin-top: 20px;
}

.nav-button {
  margin-bottom: 10px;
  cursor: pointer;
}

.nav-button img {
  width: 60px;
  height: auto;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.top-bar {
  height: 60px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 12px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.system-name {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.home-button {
  margin-left: 20px;
  cursor: pointer;
}

.current-time {
  margin-left: auto;
  color: #666;
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.user-button {
  cursor: pointer;
  margin-right: 10px;
}

.username {
  color: #333;
}

.annotation-content {
  padding: 30px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
  margin: 20px;
}

.task-list-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}
.dialog-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.operation-normal-button,
.operation-delete-button,
.operation-share-button {
  width: 30px;
}
.operation_column div img {
  width: 30px;
  height: auto;
}

</style>


